﻿using System.Web.Http.OData.Routing;

namespace CloudNinja.Metering.Web.App_Start
{
    using System.Collections.Generic;
    using System.Net.Http;
    using System.Web.Http;
    using System.Web.Http.OData.Batch;
    using System.Web.Http.OData.Builder;
    using System.Web.Http.OData.Routing;
    using System.Web.Http.OData.Routing.Conventions;

    using CloudNinja.Metering.Data.Models;

    using Microsoft.Data.Edm;

    using Newtonsoft.Json;

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Make JSON serialization handling UTC by default
            var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
            json.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
            json.SerializerSettings.DateParseHandling = DateParseHandling.DateTime;
            json.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;

            // Web API routes
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional });

            var builder = new ODataConventionModelBuilder();
            builder.EntitySet<MeterData>("MeterData");
            builder.EntitySet<MonthlyView>("MonthlyView");
            builder.EntitySet<TotalResourceUsage>("TotalResourceUsage");
            builder.EntitySet<MeterData>("MeterData");
            builder.EntitySet<TotalDailyView>("TotalDailyView");
            builder.EntitySet<TotalMonthlyView>("TotalMonthlyView");
            builder.EntitySet<MeterData>("MeterDataRepository");

            config.Routes.MapODataRouteWithHandler("odata", "odata", builder.GetEdmModel(), UnityConfig.GetHmacHandler(config));
        }

        // This is a clone of the MapODataRoute method coming from the WebApi OData nuget package. Original was not exposing a HttpMessageHandler 
        private static void MapODataRouteWithHandler(this HttpRouteCollection routes, string routeName, string routePrefix, IEdmModel model, HttpMessageHandler handler)
        {
            var pathHandler = new DefaultODataPathHandler();
            var routingConventions = ODataRoutingConventions.CreateDefault();

            if (!string.IsNullOrEmpty(routePrefix))
            {
                var num = routePrefix.Length - 1;
                if (routePrefix[num] == '/')
                {
                    routePrefix = routePrefix.Substring(0, routePrefix.Length - 1);
                }
            }

            var pathConstraint = new ODataPathRouteConstraint(pathHandler, model, routeName, routingConventions);
            
            routes.Add(routeName, new ODataRoute(routePrefix, pathConstraint, null, null, null, handler));
        }
    }
}
